#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h> 
#include <sys/ioctl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <termios.h> 
#include "linux/i2c-dev.h"
#include "drv_i2c.h"


int drv_i2cOpen(void)
{
	int fd = 0;
	fd = open("/dev/i2c-1", O_RDWR);
	if (fd < 0) 
	{
		printf("Error on open i2c \n");
		exit(1);
	}
	return fd;
}

int drv_i2cClose(int fd)
{
	printf("close i2c \n");
	return close(fd);
}

void drv_i2cSetDevice(int fd, int address)
{
	if (ioctl(fd, I2C_SLAVE, address) < 0)
	{
		printf("Error i2c on slave address\n");
	}
}

void drv_i2cWriteByte(int fd,int reg, char data)
{
	char buf[2];
        buf[0] = reg;
        buf[1] = data;
        if ((write(fd,buf,2))!=2) 
        {
		printf("Error i2c on write\n");
	}
}

char drv_i2cReadByte(int fd, int reg)
{
	char buf[1];
        buf[0] = reg;
        if ((write(fd,buf,1))!=1) 
	{
		printf("Error i2c on select\n");
        }
        if ((read(fd,buf,1))!=1) 
	{
                printf("Error i2c on read\n");
        }
	return buf[0];
}



signed short drv_i2cReadShort(int fd, int reg)
{
	unsigned char msb, lsb;
	msb = drv_i2cReadByte(fd, reg);
	lsb = drv_i2cReadByte(fd, reg + 1);

	return (signed short)((unsigned short)msb<<8 | lsb);
}
